package it.jx.wormholes.ui;

import java.awt.*;
import javax.swing.*;
import it.jx.wormholes.physics.*;
import java.util.Vector;

public class WorldView extends JComponent implements Runnable {
	private Thread asThread;
	private Vector<Mass> masses;
	private double scaleFactor;
	private double maxFrameRate;
	
	public WorldView(int width, int height, double scaleFactor, double maxFrameRate) {
		setPreferredSize(new Dimension(width, height));
		this.scaleFactor = scaleFactor;
		this.maxFrameRate = maxFrameRate;
		this.setDoubleBuffered(true);
		asThread = null;
		masses = new Vector<Mass>();
	}
	
	public void startView() {
		if (asThread == null) {
			asThread = new Thread(this);
			asThread.start();
		}
	}
	
	public void addMass(Mass m) {
		masses.add(m);
	}
	
	public void stopView() {
		if (asThread != null)
			asThread = null;
	}
	
	@Override
	public void run() {
		long ct;
		
		while (asThread != null) {
			ct = System.currentTimeMillis();
			
			repaint();
			
			try {
				Thread.sleep((long)(1.0 / maxFrameRate * 1000.0) - (System.currentTimeMillis() - ct));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void paintComponent(Graphics graphics) {
		Graphics2D g = (Graphics2D)graphics;
		
		// Draws background
		g.setColor(Color.white);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		// Draws masses
		int sx, sy;
		
		g.setColor(Color.black);
		for (Mass m : masses) {
			sx = (int)(m.position.x * scaleFactor) + getWidth() / 2;
			sy = (int)(m.position.y * scaleFactor) + getHeight() / 2;
			
			g.drawOval(sx - 3, sy - 3, 6, 6);
		}
	}

}
